package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.EmployeeLoanContent;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.DateUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;

public class AddTravelReimburseListDetailFragment extends TravelReimburseListDetailFragment {
  public static final String EXTRA_TRAVELREIMBURSE_CONTENT =
      "com.isunland.managesystem.ui.EXTRA_EXTRA_TRAVELREIMBURSE_CONTENT";
  private EmployeeLoanContent mEmployeeLoanContent;

  // 创建菜单
  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_confirm, menu);
    mEmployeeLoanContent =
        (EmployeeLoanContent) getArguments().getSerializable(EXTRA_TRAVELREIMBURSE_CONTENT);
    super.onCreateOptionsMenu(menu, inflater);
  }

  // 初始化控件
  protected void initData() {
    //		//连网获取交通工具类型和id
    //		tvtraftool.setOnClickListener(new OnClickListener() {
    //
    //			@Override
    //			public void onClick(View arg0) {DialogFragment dialog = null;
    //			FragmentManager fm = getActivity().getSupportFragmentManager();
    //
    //				dialog = new TrafToolDialogFragment();
    //
    //			dialog.setTargetFragment(AddTravelReimburseListDetailFragment.this,
    //					TRAFTOOL);
    //			dialog.show(fm, "");
    //			}
    //		});
    // 详情
  }

  // 菜单点击事件
  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      case R.id.menu_item_confirm:
        boolean allEmpty = allEmpty();
        if (allEmpty) {
          Toast.makeText(getActivity(), R.string.nothing, Toast.LENGTH_SHORT).show();
        } else {
          if (!TextUtils.isEmpty(etstartDate.getText().toString()) && !TextUtils.isEmpty(
              etendDate.getText().toString())) {
            String startTime = etstartDate.getText().toString();
            String endTime = etendDate.getText().toString();
            LogUtil.i("before==" + DateUtil.before(startTime, endTime));
            if (DateUtil.before(startTime, endTime)) {
              volleyPostSave();
            } else {
              ToastUtil.show(R.string.reachTimeBeforeStartTime);
            }
          } else {
            volleyPostSave();
          }
        }
        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  private void volleyPostSave() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TRAVEL_LIST_SAVE);

    HashMap<String, String> params = new HashMap<String, String>();
    HashMap<String, String> paramsItem = new HashMap<String, String>();

    //类型和id是从主表传递过来的
    paramsItem.put("SUBDOCTYPE", mEmployeeLoanContent.getCertificateName());//单据明细类型
    paramsItem.put("SUBDOCTYPEID", mEmployeeLoanContent.getCertificateCode());//单据明细类型ID
    //出差人姓名和id
    paramsItem.put("TRAVELER", mEmployeeLoanContent.getReceiverName());//出差人
    paramsItem.put("TRAVELERID", mEmployeeLoanContent.getReceiverId());//出差人ID

    paramsItem.put("LEAVE_TIME", etstartDate.getText().toString());
    paramsItem.put("LEAVE_PLACE", etstartEar.getText().toString());
    paramsItem.put("ARRIVE_TIME", etendDate.getText().toString());
    paramsItem.put("ARRIVE_PLACE", etendEar.getText().toString());
    // 连网获取交通工具
    if (!TextUtils.isEmpty(mId)) {
      paramsItem.put("TRAFTOOL", tvtraftool.getText().toString());//连网获取交通工具
      paramsItem.put("TRAFTOOLID", mId);//连网获取交通工具的id
    }
    paramsItem.put("TRAFTOOL_COST", ettraftoolCost.getText().toString());//交通费
    paramsItem.put("]", tvallStandard.getText().toString());//出差补贴总计
    paramsItem.put("GRANT_STANDARD", etstandard.getText().toString());//出差补贴标准
    paramsItem.put("CITY_TRAFIC_FEE", etcityCost.getText().toString());//市内交通费
    paramsItem.put("TOFFSET_DAYS", ettravelDays.getText().toString());//出差补贴天数
    paramsItem.put("TOOL_OFFSET", etnbuyCost.getText().toString());//不买卧铺补贴
    paramsItem.put("HOTEL_FEE", etliveCost.getText().toString());//住宿费
    paramsItem.put("OTHER_FEE", etotherCost.getText().toString());//其他费用
    paramsItem.put("TCOST_BILLNUM", etPages.getText().toString());//单据张数
    paramsItem.put("COST_SUBTOTAL", tvbillFee.getText().toString());//票据费用
    paramsItem.put("TICKETS_NUM", etcertificateNo.getText().toString());//票据号
    paramsItem.put("NOTE", etNote.getText().toString());//备注
    paramsItem.put("SUM_BILL_FEE", tvallCost.getText().toString());//费用金额
    String test = new JSONObject(paramsItem).toString();
    LogUtil.d(test);
    params.put("json", test);
    params.put("regJobNo ", mCurrentUser.getJobNumber());//申请人工号
    params.put("mainId", mEmployeeLoanContent.getId());//主表id

    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        LogUtil.i(arg0);
        // 解析响应的字符串
        SuccessMessage[] result = new Gson().fromJson(arg0, SuccessMessage[].class);
        SuccessMessage workProcess = result[0];

        if (null == workProcess || null == workProcess.getResult()) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;
    //		if (requestCode == TRAFTOOL && data != null) {
    //			CustomerDialog customer = (CustomerDialog) data
    //					.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
    //			mName=customer.getName();
    //			mId=customer.getId();
    //			tvtraftool.setText(mName);//交通工具
    //			return;
    //		}
    super.onActivityResult(requestCode, resultCode, data);
  }

  // fragment之间传值
  public static AddTravelReimburseListDetailFragment newInstance(EmployeeLoanContent item) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_TRAVELREIMBURSE_CONTENT, item);
    AddTravelReimburseListDetailFragment fragment = new AddTravelReimburseListDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
